package app.project.directionlensproject.map;

import java.util.ArrayList;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import app.project.directionlensproject.HomeActivity;
import app.project.directionlensproject.ListPlaceActivity;
import app.project.directionlensproject.MyApplication;
import app.project.directionlensproject.R;
import app.project.directionlensproject.compasspro.RotationVectorCompass;
import app.project.directionlensproject.model.Place;
import app.project.directionlensproject.serverapi.ServerAPI;
import app.project.directionlensproject.util.AsyncTask;
import app.project.directionlensproject.util.BundleKeys;
import app.project.directionlensproject.util.CommonUtils;
import app.project.directionlensproject.util.Constants;
import app.project.directionlensproject.util.DialogUtils;
import app.project.directionlensproject.util.GPSTracker;
import app.project.directionlensproject.util.GetDataTask;
import app.project.directionlensproject.util.IGetDataTask;
import app.project.directionlensproject.util.Utilities;

public class MapActivity extends Activity {

	private GoogleMap map;
	public static final LatLng FPT = new LatLng(21.029151, 105.782222);

	/* put this into your activity class */
	private SensorManager mSensorManager;

	private LinearLayout layoutMapView1, layoutMapView2;
	//private RotateCameraSurface mViewCamera;
	private ArrayList<Place> arrPlaces = new ArrayList<Place>();
	ArrayList<Place> placeInAngle = new ArrayList<Place>();
	private int categoryID = 0;
	private boolean isUserPlace;

	private ImageView mImageViewZoomPlace;
	private TextView mTextViewUser;
	LatLng MYPLACE;

	ArrayList<Integer> startY;
	int startRow = 3;
	int rowHeight=40;
	
	@Override
	public void onCreate(Bundle circle) {
		super.onCreate(circle);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().setFormat(PixelFormat.RGBA_8888);
		
		setContentView(R.layout.activity_map);
		
		startY = new ArrayList<Integer>();
		for(int i=0;i<5;i++){
			startY.add(i);
		}
		categoryID = getIntent().getIntExtra(BundleKeys.CATE_ID,
				Constants.ID_C_ALL);
		
		Log.e("CategoryInMap",categoryID+"");
		
		isUserPlace = getIntent().getBooleanExtra(BundleKeys.IS_USER_PLACE,
				false);

		MYPLACE = new LatLng(HomeActivity.MY_LATITUDE,
				HomeActivity.MY_LONGITUDE);

		String nameUser = CommonUtils.getStringSetting(MapActivity.this,
				Constants.USER_NAME, "Guest");
		mTextViewUser = (TextView) findViewById(R.id.textViewUserName);
		mTextViewUser.setText(getResources().getString(R.string.name_hello)+" "+ nameUser);
		mTextViewUser.setOnClickListener(onClickUserName);

		/* do this in onCreate */
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mSensorManager.registerListener(mSensorListener,
				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);

		GPSTracker gps;
		gps = new GPSTracker(MapActivity.this);
		// check if GPS enabled
		if (gps.canGetLocation()) {
			double latitude = gps.getLatitude();
			double longitude = gps.getLongitude();
			Log.e("Value", "Lat=" + latitude + "/Long=" + longitude);
		}
		createMapView1();
		createMapView2();

	}

	/**
	 * event when click user name
	 */
	private OnClickListener onClickUserName = new OnClickListener() {

		public void onClick(View arg0) {
			// display dialog option
			if (CommonUtils.getStringSetting(MapActivity.this,
					Constants.TOKEN_ID, null) != null) {
				DialogUtils.showDialogUser(MapActivity.this,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								if (which == 0) {// my place
									Intent i = new Intent(MapActivity.this,
											ListPlaceActivity.class);
									i.putExtra(BundleKeys.IS_USER_PLACE, true);
									startActivity(i);
								} else if (which == 1) {// change pass
									HomeActivity.TYPE_HOME = HomeActivity.TYPE_CHANGEPASS;
									finish();
								} else {// logout
									// isLogin = false;
									CommonUtils.saveStringSetting(
											MapActivity.this,
											Constants.TOKEN_ID, null);
									mTextViewUser
											.setText(getString(R.string.hello)
													+ " Guest");
									CommonUtils.saveStringSetting(
											MapActivity.this,
											Constants.TOKEN_ID, null);
									Toast.makeText(getApplicationContext(),
											R.string.logout_sucess,
											Toast.LENGTH_LONG).show();
								}
							}
						});

			} else {
				HomeActivity.TYPE_HOME = HomeActivity.TYPE_LOGIN;
				finish();
			}
		}
	};

	/**
	 * create mapview when device display portrait
	 */
	private void createMapView2() {
		layoutMapView2 = (LinearLayout) findViewById(R.id.layoutMapView2);
	}

	/**
	 * create mapview when device parallel of land
	 */
	@SuppressLint("NewApi")
	private void createMapView1() {

		mImageViewZoomPlace = (ImageView) findViewById(R.id.imageViewZoomMyPlace);
		layoutMapView1 = (LinearLayout) findViewById(R.id.layoutMapView1);

		map = ((MapFragment) getFragmentManager().findFragmentById(
				R.id.mapFragment)).getMap();
		map.moveCamera(CameraUpdateFactory.newLatLngZoom(MYPLACE, 20));

		MarkerOptions mkOptionUser = new MarkerOptions();
		mkOptionUser.position(MYPLACE);
		mkOptionUser.title("My location");
		mkOptionUser.snippet("");
		mkOptionUser.icon(BitmapDescriptorFactory
				.fromResource(R.drawable.ic_marker_my_place));

		map.addMarker(mkOptionUser);

		Utilities.getInstance()
				.drawCircle(
						map,
						MYPLACE.latitude,
						MYPLACE.longitude,
						CommonUtils.getIntSetting(MapActivity.this,
								Constants.RADIUS, 5) * 1000);

		// Zoom in, animating the camera.
		map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
		map.setOnInfoWindowClickListener(inforWindowClickListener);

		if (getIntent().getIntExtra(BundleKeys.PREV_PAGE,
				Constants.FROM_CATEGORY) == Constants.FROM_CATEGORY) {
			setDataFromCategory();
		} else {
			setDataFromListPlace();
		}

		mImageViewZoomPlace.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				map.moveCamera(CameraUpdateFactory.newLatLngZoom(MYPLACE, 20));
				// Zoom in, animating the camera.
				map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
			}
		});
	}

	/**
	 * set data if from list place activity
	 */
	private void setDataFromListPlace() {
		arrPlaces = ListPlaceActivity.listCurrentPlace;
		if (arrPlaces != null) {
			for (int i = 0; i < arrPlaces.size(); i++) {
				MarkerOptions mkOption = new MarkerOptions();
				mkOption.position(new LatLng(arrPlaces.get(i).locationx,
						arrPlaces.get(i).locationy));
				mkOption.title(arrPlaces.get(i).placename);
				mkOption.snippet(arrPlaces.get(i).description);
				mkOption.icon(Utilities.getInstance()
						.getBitmapDescriptionFromType(
								arrPlaces.get(i).categoryid));
				if(arrPlaces.get(i).categoryid==0){
					mkOption.icon(Utilities.getInstance()
							.getBitmapDescriptionFromType(categoryID));
				}
				map.addMarker(mkOption);
			}
		}
	}

	/**
	 * set data if from category
	 */
	private void setDataFromCategory() {
		new GetDataTask(MapActivity.this, new IGetDataTask() {

			@Override
			public boolean doInBackGround() throws Exception {
				double locationX = HomeActivity.MY_LATITUDE;
				double locationY = HomeActivity.MY_LONGITUDE;
				arrPlaces = ServerAPI.GetNearbyPlace(categoryID, locationX,
						locationY, CommonUtils.getIntSetting(MapActivity.this,
								Constants.RADIUS, 5), 0, 100);
				return false;
			}

			@Override
			public void onPostExecute(boolean result) throws Exception {
				super.onPostExecute(result);

				if (arrPlaces == null) {
					//Log.e("ArrPlace", "Null");
					arrPlaces = new ArrayList<Place>();

				} else {
					//Log.e("ArrPlace", arrPlaces.size() + "");
					for (int i = 0; i < arrPlaces.size(); i++) {
						//Log.e("LatLong", "Lat" + i + "="
								//+ arrPlaces.get(i).locationx + "---" + "Long"
								//+ i + "=" + arrPlaces.get(i).locationy);
						MarkerOptions mkOption = new MarkerOptions();
						mkOption.position(new LatLng(
								arrPlaces.get(i).locationx,
								arrPlaces.get(i).locationy));
						mkOption.title(arrPlaces.get(i).placename);
						mkOption.snippet(arrPlaces.get(i).description);
						mkOption.icon(Utilities.getInstance()
								.getBitmapDescriptionFromType(
										arrPlaces.get(i).categoryid));
						map.addMarker(mkOption);
					}

				}
			}

		}, false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	// Event when click in window infor of maker
	OnInfoWindowClickListener inforWindowClickListener = new OnInfoWindowClickListener() {

		public void onInfoWindowClick(Marker maker) {
			// TODO Auto-generated method stub
			// Go to page detail of place
			String title = maker.getTitle();
			int position = Utilities.getInstance().getPositionMakerSelect(
					title, arrPlaces);
			Intent it = new Intent(MapActivity.this,
					PlaceDetailActivity.class);
			it.putExtra("place", arrPlaces.get(position));
			startActivity(it);
		}
	};

	private boolean isFinish = false;
	/**
	 * event sensor of device change
	 */
	private final SensorEventListener mSensorListener = new SensorEventListener() {
		// private boolean isFinish = false;

		public void onSensorChanged(SensorEvent se) {
			// Thang dung theo chieu doc thi y lon nhat
			// Thang dung theo chieu ngang thi x lon nhat
			// Nam mat song song voi mat dat thi z lon nhat
			float x = se.values[0];
			float y = se.values[1];
			float z = se.values[2];

			if (x > y && x > z) {
				Intent it=new Intent(MapActivity.this,RotationVectorCompass.class);
				it.putExtra(BundleKeys.IS_MAP, true);
				it.putExtra(BundleKeys.IS_USER_PLACE, isUserPlace);
				it.putExtra(BundleKeys.CATE_ID, categoryID);
				startActivity(it);				
			}
			if (y > x && y > z) {
				layoutMapView1.setVisibility(View.GONE);
				layoutMapView2.setVisibility(View.GONE);
				if (!isFinish) {
					ListPlaceActivity.isCompass=false;
					ListPlaceActivity.isFinish=false;
					Intent i = new Intent(MapActivity.this,
							ListPlaceActivity.class);
					if(HomeActivity.isListAll){
						i.putExtra(BundleKeys.IS_USER_PLACE,false);
					}else{
						i.putExtra(BundleKeys.IS_USER_PLACE,true);
					}
					i.putExtra(BundleKeys.CATE_ID, categoryID);
					startActivity(i);
					MapActivity.this.finish();
					isFinish = true;
				}

			}
			if (z > x && z > y) {
				layoutMapView1.setVisibility(View.VISIBLE);
				layoutMapView2.setVisibility(View.GONE);
			}

		}

		public void onAccuracyChanged(Sensor sensor, int accuracy) {
		}
	};

	@Override
	public void onConfigurationChanged(
			android.content.res.Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			if (!isFinish) {
//				Intent i = new Intent(MapActivity.this, ListPlaceActivity.class);
//				i.putExtra(BundleKeys.IS_USER_PLACE, isUserPlace);
//				i.putExtra(BundleKeys.CATE_ID, categoryID);
//				startActivity(i);
//				MapActivity.this.finish();
//				isFinish = true;
				ListPlaceActivity.isCompass=false;
				ListPlaceActivity.isFinish=false;
				Intent i = new Intent(MapActivity.this,
						ListPlaceActivity.class);
				if(HomeActivity.isListAll){
					i.putExtra(BundleKeys.IS_USER_PLACE,false);
				}else{
					i.putExtra(BundleKeys.IS_USER_PLACE,true);
				}
				i.putExtra(BundleKeys.CATE_ID, categoryID);
				startActivity(i);
				MapActivity.this.finish();
				isFinish = true;
			}
		}
	}

	
	public boolean IsSpaceAvailable(Activity mActivity,
			float rotate) {
		Display localDisplay2 = mActivity.getWindowManager()
				.getDefaultDisplay();
		Point localPoint = new Point();
		localDisplay2.getSize(localPoint);
		int width = localPoint.x;
		//int height = localPoint.y;
		int mGapBetweenRects = 10;
		int bitmapWidth = 30;
		int rectWidth = 80;

		return (int) (4.0F * ((180.0F + rotate) / 360.0F * width)) >= ((Integer) startY
				.get(-1 + startY.size())).intValue()
				+ rectWidth
				+ bitmapWidth
				+ mGapBetweenRects;				
	}

	public void InsertItem(Activity mActivity, int paramInt, float rotate) {

		Display localDisplay2 = mActivity.getWindowManager()
				.getDefaultDisplay();
		Point localPoint = new Point();
		localDisplay2.getSize(localPoint);
		int width = localPoint.x;
//		int height = localPoint.y;
//		int mGapBetweenRects = 10;
		int i = (int) (4.0F * ((180.0F + rotate) / 360.0F * width));
		startY.add(Integer.valueOf(i));
		// rowInfo[paramInt].placeItem.add(paramStringList);
	}
	// Event when click maker in mapview

	@Override
	protected void onResume() {
		super.onResume();
		//mGLSurfaceView.onResume();
		mSensorManager.registerListener(mSensorListener,
				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	@Override
	protected void onPause() {
		mSensorManager.unregisterListener(mSensorListener);
		//mGLSurfaceView.onPause();
		super.onPause();
	}

	
	
//	@Override
//	public void onBackPressed() {
//		super.onBackPressed();
//	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	MapActivity.this.finish();
	    	startActivity(new Intent(MapActivity.this,HomeActivity.class));
	    	//go to category	    		    	
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
}